package org.example.attendancesystem.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.*;
import org.example.attendancesystem.domain.*;
import org.example.attendancesystem.domain.vo.AttendanceRecordWithTitleVO;
import org.example.attendancesystem.mapper.AttendanceRecordsMapper;
import org.example.attendancesystem.service.AttendanceRecordsService;
import org.example.attendancesystem.service.SessionParamsService;
import org.example.attendancesystem.service.StudentsService;
import org.example.attendancesystem.service.impl.StudentsServiceImpl;
import org.gavaghan.geodesy.Ellipsoid;
import org.gavaghan.geodesy.GeodeticCalculator;
import org.gavaghan.geodesy.GeodeticCurve;
import org.gavaghan.geodesy.GlobalCoordinates;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.security.PrivateKey;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2025-04-13
 */
@CrossOrigin
@RestController
@RequestMapping("/attendance-records")
public class AttendanceRecordsController {
    @Autowired
    private AttendanceRecordsService attendanceRecordsService;
    @Autowired
    private AttendanceRecordsMapper attendanceRecordsMapper;
    @Autowired
    private StudentsService studentsService;
    @Autowired
    SessionParamsService sessionParamsService;
//查询对应学生id签到数量
    @GetMapping("/getAttentanceCmount")
    public Result<List<AttendanceRecords>> getAttendanceCmount(@RequestParam("studentId") Long studentId) {
        QueryWrapper<AttendanceRecords> wrapper = new QueryWrapper<AttendanceRecords>()
                .eq("student_id", studentId)
                .eq("status","未签到");
        List<AttendanceRecords> list = attendanceRecordsService.list(wrapper);
        return Result.success(list);
    }
    //更新普通签到数据
    @PostMapping("/CommonupdateCommon")
    public  Result<String> addAttendanceRecords(@RequestParam("recordId")Long recordId) {
        LambdaUpdateWrapper<AttendanceRecords> updateChainWrapper = new LambdaUpdateWrapper<AttendanceRecords>()
                .eq(AttendanceRecords::getRecordId,recordId)
                .set(AttendanceRecords::getStatus,"已签到");
        boolean res = attendanceRecordsService.update(updateChainWrapper);
        if (res){
            return Result.success("success");
        }else {
            return Result.fail("fail");
        }
    }
//查询普通签到数据
    @GetMapping("/queryCommonData")
    public Result<List<AttendanceRecordWithTitleVO>> queryCommonData(@RequestParam("studentId") Long studentId) {
        List<AttendanceRecordWithTitleVO> list= attendanceRecordsMapper.selectCommonRecordsWithTitleByStudentId(studentId.toString());
        return Result.success(list);
    }
    //查询签到码签到数据
    @GetMapping("/querySignCodeData")
    public Result<List<AttendanceRecordWithTitleVO>>querySiignCodeData(@RequestParam("studentId") Long studentId){
        List<AttendanceRecordWithTitleVO> list= attendanceRecordsMapper.selectSignCodeRecordsWithTitleByStudentId(studentId.toString());
        return Result.success(list);

    }
    @GetMapping("/list")
    public Result<IPage<Records>> getAll(
            @RequestParam int currentPage,  // 修正参数名（前端传的是currentPage）
            @RequestParam int pageSize,
            @RequestParam int id,
            @RequestParam(required = false) String studentId,
            @RequestParam(required = false) String status) {
        Page<AttendanceRecords> page = new Page<>(currentPage, pageSize);
        QueryWrapper<AttendanceRecords> wrapper = new QueryWrapper<>();
        if(studentId != null && !studentId.isEmpty()) {
            wrapper.eq("student_id", studentId);
        }
        if(status != null && !status.isEmpty()) {
            wrapper.eq("status", status);
        }
//        System.out.println(id);
        wrapper.eq("session_id", id);
        IPage<AttendanceRecords> attendanceSessionsPage = attendanceRecordsService.page(page, wrapper);
//        System.out.println(attendanceSessionsPage.getRecords());
        IPage<Records> recordsIPage = attendanceSessionsPage.convert(attendanceRecords -> {
            Records records = new Records();
            records.setRecordId(attendanceRecords.getRecordId());
            records.setStudentId(attendanceRecords.getStudentId());
            records.setName(studentsService.getById(attendanceRecords.getStudentId()).getName());
            records.setStatus(attendanceRecords.getStatus());
            records.setSessionId(attendanceRecords.getSessionId());
            records.setSignTime(attendanceRecords.getSignTime());
            return records;
        });

        return Result.success(recordsIPage);
    }
    @PutMapping("/update/{id}")
    public Result<String> update(@PathVariable("id") Long id, @RequestBody Status status) {
        System.out.println(id+" "+status);
        AttendanceRecords attendanceRecords = attendanceRecordsService.getById(id);
        attendanceRecords.setStatus(status.getStatus());
        boolean isSuccess = attendanceRecordsService.updateById(attendanceRecords);
        if (isSuccess) {
            return Result.success("更新成功");
        } else {
            return Result.fail("更新失败");
        }
    }
    @GetMapping("/export")
    public void exportRecords(
            @RequestParam Long id,
            @RequestParam(required = false) String studentId,
            @RequestParam(required = false) String status,
            HttpServletResponse response) {

        try {
            // 1. 构建查询条件
            QueryWrapper<AttendanceRecords> wrapper = new QueryWrapper<>();
            wrapper.eq("session_id", id);

            if (StringUtils.isNotBlank(studentId)) {
                wrapper.eq("student_id", studentId);
            }

            if (StringUtils.isNotBlank(status)) {
                wrapper.eq("status", status);
            }

            // 2. 查询数据
            List<AttendanceRecords> records = attendanceRecordsService.list(wrapper);

            // 3. 创建Excel工作簿
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet("签到记录");

            // 4. 创建表头
            String[] headers = {"学号", "姓名", "状态", "签到时间"};
            HSSFRow headerRow = sheet.createRow(0);
            for (int i = 0; i < headers.length; i++) {
                HSSFCell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
            }

            // 5. 填充数据
            int rowNum = 1;
            for (AttendanceRecords record : records) {
                HSSFRow row = sheet.createRow(rowNum++);
                row.createCell(0).setCellValue(record.getStudentId());
                row.createCell(1).setCellValue(studentsService.getById(record.getStudentId()).getName());
                row.createCell(2).setCellValue(record.getStatus());

                // 处理日期格式
                HSSFCell dateCell = row.createCell(3);
                if (record.getSignTime() != null) {
                    dateCell.setCellValue(record.getSignTime());
                    HSSFCellStyle style = workbook.createCellStyle();
                    style.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));
                    dateCell.setCellStyle(style);
                }
            }

            // 6. 设置响应头
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition",
                    "attachment; filename=attendance_records_" + System.currentTimeMillis() + ".xlsx");

            // 7. 写入响应流
            workbook.write(response.getOutputStream());
            workbook.close();

        } catch (Exception e) {
            throw new RuntimeException("导出失败", e);
        }
    }
    @PostMapping("/local_sign_in")
    public Result<String> localSignIn(@RequestBody Position position) {
        Long recordId = position.getRecordId();
        String studentId = position.getStudentId();
        AttendanceRecords attendanceRecord = attendanceRecordsService.getById(recordId);
        SessionParams session = sessionParamsService.getById(attendanceRecord.getSessionId());
        Double lon1 = position.getLongitude().doubleValue();
        Double lat1 = position.getLatitude().doubleValue();
        Double lon2 = session.getLongitude().doubleValue();
        Double lat2 = session.getLatitude().doubleValue();
        GlobalCoordinates source = new GlobalCoordinates(lon1, lat1);
        GlobalCoordinates target = new GlobalCoordinates(lon2, lat2);

        GeodeticCurve geoCurve = new GeodeticCalculator().calculateGeodeticCurve(Ellipsoid.WGS84, source, target);
        Double distance = geoCurve.getEllipsoidalDistance();
        System.out.println(distance);
        int radius = session.getRadius();
        if(distance<radius)
        {
            LambdaUpdateWrapper<AttendanceRecords> updateChainWrapper = new LambdaUpdateWrapper<AttendanceRecords>()
                    .eq(AttendanceRecords::getRecordId, recordId)
                    .eq(AttendanceRecords::getStudentId, studentId)
                    .set(AttendanceRecords::getStatus, "已签到");
            boolean res = attendanceRecordsService.update(updateChainWrapper);
            if (res) {
                return Result.success("签到成功");
            } else {
                return Result.fail("签到失败");
            }
        }
        else {
            return Result.fail("不在签到范围内");
        }
    }
//    @PostMapping("/scanQRCode")
//    public Result<String> scanQRCode(@RequestBody AttendanceSessionData sessionData) {
//        // 获取二维码中传递的签到会话数据
//        Long sessionId = sessionData.getSessionId();
//        Long studentId = sessionData.getStudentId();
//
//        // 查询二维码对应的签到会话
//        AttendanceRecords session = attendanceRecordsService.getById(sessionId);
//
//        // 校验会话是否存在
//        if (session == null) {
//            return Result.fail("签到会话不存在");
//        }
//
//
//
//        // 查询学生的签到记录
//        QueryWrapper<AttendanceRecords> wrapper = new QueryWrapper<>();
//        wrapper.eq("session_id", sessionId)
//                .eq("student_id", studentId);
//        AttendanceRecords record = attendanceRecordsService.getOne(wrapper);
//
//        // 如果记录已存在，判断是否已签到
//        if (record != null) {
//            if ("已签到".equals(record.getStatus())) {
//                return Result.fail("您已经签到");
//            } else {
//                // 更新签到状态为已签到
//                LambdaUpdateWrapper<AttendanceRecords> updateWrapper = new LambdaUpdateWrapper<>();
//                updateWrapper.eq(AttendanceRecords::getRecordId, record.getRecordId())
//                        .set(AttendanceRecords::getStatus, "已签到");
//                boolean updateResult = attendanceRecordsService.update(updateWrapper);
//
//                if (updateResult) {
//                    return Result.success("扫码签到成功");
//                } else {
//                    return Result.fail("签到失败");
//                }
//            }
//        } else {
//            return Result.fail("未找到该学生的签到记录");
//        }
//    }
@PostMapping("/scanQRCode")
public Result<String> scanQRCode(@RequestBody AttendanceSessionData sessionData) {
    Long sessionId = sessionData.getSessionId();
    Long studentId = sessionData.getStudentId();

    // 打印 sessionId 和 studentId，调试用
    System.out.println("Session ID: " + sessionId);
    System.out.println("Student ID: " + studentId);

    // 查询二维码对应的签到会话
    AttendanceRecords session = attendanceRecordsService.getBySessionId(sessionId);

    // 校验会话是否存在
    if (session == null) {
        System.out.println("签到会话不存在");
        return Result.fail("签到会话不存在");

    }

    // 查询学生的签到记录
    QueryWrapper<AttendanceRecords> wrapper = new QueryWrapper<>();
    wrapper.eq("session_id", sessionId)
            .eq("student_id", studentId);
    AttendanceRecords record = attendanceRecordsService.getOne(wrapper);

    // 如果学生签到记录存在，则更新状态为已签到
    if (record != null) {
        LambdaUpdateWrapper<AttendanceRecords> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(AttendanceRecords::getRecordId, record.getRecordId())
                .set(AttendanceRecords::getStatus, "已签到");

        // 更新签到状态
        boolean updateResult = attendanceRecordsService.update(updateWrapper);

        // 返回更新结果
        if (updateResult) {
//            System.out.println("扫码签到成功");
            return Result.success("扫码签到成功");
        } else {
//            System.out.println("扫码签到shibai");
            return Result.fail("签到失败");
        }
    } else {
        // 如果没有找到该学生的签到记录
//        System.out.println("meizhaodao");
        return Result.fail("未找到该学生的签到记录");
    }
}


}
